//
//  AMInstancesTableView.m
//  AWSMobile
//
//  Created by James on 14-10-27.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "AMInstancesTableView.h"
#import <Bolts/BFTask.h>
#import <Bolts/BFExecutor.h>
#import <AWSiOSSDKv2/EC2.h>

#import "AMInstanceCell.h"
#import "AMInstanceDetailView.h"

#import "AMConstants.h"
#import "AMFunctions.h"
#import "AWSEC2Instance+Extension.h"


@interface AMInstancesTableView ()

@property (nonatomic) NSArray *allInstances;

@property AWSEC2DescribeInstancesRequest *listInstancesRequest;
@property AWSEC2StartInstancesRequest *startInstanceRequest;
@property AWSEC2StopInstancesRequest *stopInstanceRequest;

@end

@implementation AMInstancesTableView

#pragma mark - Setter ang getter

- (NSArray *)allInstances
{
    return _allInstances;
}

#pragma mark - Life cycle

- (void)viewWillAppear:(BOOL)animated
{
    [self refreshInstances:nil];
}

-(void)viewWillDisappear:(BOOL)animated
{
    if (_listInstancesRequest)
    {
        [_listInstancesRequest cancel];
        _listInstancesRequest = nil;
    }
    if (_startInstanceRequest)
    {
        [_startInstanceRequest cancel];
        _startInstanceRequest = nil;
    }
    if (_stopInstanceRequest)
    {
        [_stopInstanceRequest cancel];
        _stopInstanceRequest = nil;
    }
    self.navigationItem.rightBarButtonItem = _refresh;
}

- (void)viewDidAppear:(BOOL)animated
{
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tabBarController.tabBar setSelectedImageTintColor:[UIColor colorWithHexString:@"36b2af"]];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_allInstances)
        return _allInstances.count;
    else
        return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIndentifier;
    AWSEC2Instance *instance = [[_allInstances[indexPath.row] instances] firstObject];
    
    NSString *instanceName = @"";
    for (AWSEC2Tag *tag in instance.tags)
    {
        if ([tag.key isEqualToString:@"Name"] && (tag.value && ![tag.value isEqualToString:@""]))
        instanceName = tag.value;
    }
    NSString *instanceID = instance.instanceId;
    NSString *instanceType = [instance typeName];
    NSString *instanceState = [instance stateName];
    
    CellIndentifier = @"InstanceCell";
    AMInstanceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier forIndexPath:indexPath];
    
    cell.instanceID.text = instanceID;
    cell.instanceType.text = instanceType;
    cell.instanceState.text = instanceState;
    cell.instanceName.text = instanceName;
    if ([instanceName isEqualToString:@""])
    {
        cell.instanceName.text = instanceID;
    }

    if (instance.state.name == AWSEC2InstanceStateNameRunning)
    {
        cell.instanceState.textColor = [UIColor colorWithHexString:@"36b2af"];
    }
    else if (instance.state.name == AWSEC2InstanceStateNameStopped || instance.state.name == AWSEC2InstanceStateNameStopping)
    {
        cell.instanceState.textColor = [UIColor colorWithHexString:@"fe93bf"];
    }
    else
    {
        cell.instanceState.textColor = [UIColor colorWithHexString:@"656565"];
    }
    
    cell.tag = 101 + indexPath.row;
  
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMInstanceCell *cell = (AMInstanceCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self performSegueWithIdentifier:@"pushDetailView" sender:cell.instanceDetail];
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIButton *button = (UIButton *)sender;
    AMInstanceCell *cell = (AMInstanceCell *)button.superview.superview.superview.superview;
    AWSEC2Instance *instance = [[_allInstances[cell.tag - 101] instances] firstObject];
    AMInstanceDetailView *view = (AMInstanceDetailView *)segue.destinationViewController;
    view.instance = instance;
}

#pragma mark - Actions
- (void)networkStarted
{
    UIActivityIndicatorView *iView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:iView];
    [iView startAnimating];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)networkStopped
{
    self.navigationItem.rightBarButtonItem = _refresh;
}

- (IBAction)refreshInstances:(UIBarButtonItem *)sender
{
    if (!_listInstancesRequest)
    {
        _listInstancesRequest = [[AWSEC2DescribeInstancesRequest alloc] init];
    }
    
    [self networkStarted];
    
    __block typeof(self) weakSelf = self;
    [[[AWSEC2 defaultEC2] describeInstances:_listInstancesRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
        if (!task.error)
        {
            weakSelf.allInstances = [[(AWSEC2DescribeInstancesResult *)task.result reservations] mutableCopy];
            [weakSelf networkStopped];
            [weakSelf.tableView reloadData];
            
        }
        else if(task.error)
        {
            NSLog(@"ec2 error..%@",task.error);
        }
        return nil;
    }];
}

- (IBAction)instanceDetail:(UIButton *)sender
{
//    [self performSegueWithIdentifier:@"pushDetailView" sender:sender];
}




@end
